
package com.rt.schedulenew.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.rt.schedulebase.dto.DictDeptDto;
import com.rt.schedulebase.dto.DictExamItemDto;
import com.rt.schedulebase.dto.DictItemGroupDto;
import com.rt.schedulebase.dto.DictScheduleRegularDefDto;
import com.rt.schedulebase.entity.DictDept;
import com.rt.schedulebase.entity.DictItemGroup;
import com.rt.schedulebase.entity.DictScheduleRegularDef;
import com.rt.schedulebase.mapper.DictItemGroupMapper;
import com.rt.schedulenew.api.*;
import com.rt.schedulenew.utils.base.CommonUtil;
import com.rt.schedulenew.utils.base.ConstantsUtil;
import com.rt.schedulenew.utils.base.LogUtil;
import com.rt.schedulenew.utils.global.JsonResult;
import com.rt.schedulenew.utils.global.JsonResultUtil;
import com.rt.schedulenew.utils.global.PageVO;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
public class DictItemGroupServiceImpl extends ServiceImpl<DictItemGroupMapper, DictItemGroup> implements IDictItemGroupService {
    @Autowired
    private IDictScheduleRegularDefService dictScheduleRegularDefService;
    @Autowired
    private CacheServiceImpl cacheServiceImpl;
    @Autowired
    private IExamSyslogService syslogService;
    @Autowired
    private IDictSerialService dictSerialService;
    @Autowired
    private IDictDeptService dictDeptService;
    @Autowired
    private DictItemGroupDetailServiceImpl dictItemGroupDetailService;

    @Override
    public JsonResult getItemGroupList(DictItemGroupDto dto) {
        Page<?> page = PageHelper.startPage(dto.getPageNo(), dto.getPageSize());
        dto.setExamClasses(CommonUtil.split2List(dto.getExamClass()));
        dto.setItemCodeList(CommonUtil.split2List(dto.getItemCode()));

        List<DictItemGroupDto> list = baseMapper.getItemGroupList(dto);
        for (DictItemGroupDto dig : list) {
            if (StringUtils.isBlank(dig.getReqDept())) {
                continue;
            }
            DictDeptDto d = new DictDeptDto();
            d.setDeptCode(dig.getReqDept());
            List<DictDept> dictDeptList = dictDeptService.getList(d);
            if(CollectionUtils.isNotEmpty(dictDeptList)){
                StringBuffer reqDictName = new StringBuffer();
                dictDeptList.forEach(dictDept->{
                    reqDictName.append("," + dictDept.getDeptName());
                });
                dig.setReqDeptName(reqDictName.substring(1));
            }
        }
        PageVO pageVO = new PageVO();
        pageVO.setPageNo(dto.getPageNo());
        pageVO.setPageSize(dto.getPageSize());
        pageVO.setTotal(page.getTotal());
        pageVO.setPages(page.getPages());
        return JsonResultUtil.success("成功", list, pageVO);
    }

    @Override
    public JsonResult getItemPackageList(DictItemGroupDto dto) {
        Page<DictItemGroupDto> page = PageHelper.startPage(dto.getPageNo(), dto.getPageSize());
        List<String> examClassList = CommonUtil.split2List(dto.getExamClass());
        dto.setExamClasses(examClassList);
        List<DictItemGroupDto> dtoList = baseMapper.getItemGroupList(dto);
        List<DictExamItemDto> examItemDtos = new ArrayList<>();
        for (DictItemGroupDto dictItemGroup : dtoList) {
            DictExamItemDto dictExamItemDto = new DictExamItemDto();
            dictExamItemDto.setExamClass(dictItemGroup.getExamClass());
            dictExamItemDto.setItemCode(dictItemGroup.getGroupCode());
            dictExamItemDto.setInputCode(dictItemGroup.getInputCode());
            dictExamItemDto.setItemName(dictItemGroup.getGroupName());
            dictExamItemDto.setIsPackage(Boolean.TRUE);
            examItemDtos.add(dictExamItemDto);
        }
        PageVO pageVO = new PageVO();
        pageVO.setPageNo(dto.getPageNo());
        pageVO.setPageSize(dto.getPageSize());
        pageVO.setTotal(page.getTotal());
        pageVO.setPages(page.getPages());
        return JsonResultUtil.success("成功", examItemDtos, pageVO);
    }

    @Override
    public JsonResult updateItemGroup(DictItemGroupDto dto) {
        if (dto.getGroupCode() == null) {
            return JsonResultUtil.failure("修改失败：groupCode不能为空");
        }
        Map<String, Object> map = new HashMap<>();
        UpdateWrapper<DictItemGroup> update = new UpdateWrapper<>();
        map.put("GROUP_CODE", dto.getGroupCode());
        update.allEq(map);
        DictItemGroup oldGroup = baseMapper.selectOne(update);
        update.set(dto.getOrgans() == null, "ORGANS", "");
        update.set(StringUtils.isBlank(dto.getInputCode()), "INPUT_CODE", "");
        update.set(StringUtils.isBlank(dto.getPatientSource()), "PATIENT_SOURCE", "");
        update.set(StringUtils.isBlank(dto.getReqDept()), "REQ_DEPT", "");
        update.set(StringUtils.isBlank(dto.getDeptCode()), "DEPT_CODE", "");
        update.set(dto.getSortNo() == null, "SORT_NO", "");
        update.set(dto.getPriorityOrder() == null, "PRIORITY_ORDER", "");
        boolean updateResult = update(dto, update);
        if (updateResult) {
            DictItemGroup newGroup = baseMapper.selectOne(update);
            newGroup.setGroupType(ConstantsUtil.GroupType.getValue(newGroup.getGroupType()));
            oldGroup.setGroupType(ConstantsUtil.GroupType.getValue(oldGroup.getGroupType()));
            String updateDesc = "[项目分组] " + dto.getGroupName() + ":" + LogUtil.compareObject(oldGroup, newGroup);
            syslogService.saveLog(ConstantsUtil.ModuleName.ITEM_GROUP.name(), ConstantsUtil.OperateName.UPDATE.getDesc(), updateDesc);
            if ("2".equals(dto.getGroupType())) {
                DictScheduleRegularDefDto regularDefDto = new DictScheduleRegularDefDto();
                regularDefDto.setExamClass(dto.getExamClass());
                List<DictScheduleRegularDef> regularDefList = dictScheduleRegularDefService.selectList(regularDefDto);
                if (regularDefList != null && !regularDefList.isEmpty()) {
                    for (DictScheduleRegularDef regularDef : regularDefList) {
                        cacheServiceImpl.clearRegularCache(regularDef.getRegularId());
                    }
                }
            }
            return JsonResultUtil.success("修改成功");
        }
        return JsonResultUtil.failure("修改失败");
    }

    @Override
    @Transactional
    public JsonResult deleteItemGroup(DictItemGroupDto dto) {
        boolean deleteResult = false;
        DictItemGroup dictItemGroup = null;
        if (dto.getGroupCode() != null) {
            QueryWrapper<DictItemGroup> qw = new QueryWrapper<>();
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("GROUP_CODE", dto.getGroupCode());
            qw.allEq(map, false);
            dictItemGroup = getOne(qw);
            deleteResult = removeByMap(map);

            dictItemGroupDetailService.removeByMap(map);
        }
        if (deleteResult) {
            syslogService.saveLog(ConstantsUtil.ModuleName.ITEM_GROUP.name(), ConstantsUtil.OperateName.DELETE.getDesc(), "[项目分组]: " + dictItemGroup.getGroupName());
            if (dictItemGroup != null && "2".equals(dictItemGroup.getGroupType())) {
                DictScheduleRegularDefDto regularDefDto = new DictScheduleRegularDefDto();
                regularDefDto.setExamClass(dictItemGroup.getExamClass());
                List<DictScheduleRegularDef> regularDefList = (List<DictScheduleRegularDef>) dictScheduleRegularDefService.selectList(regularDefDto);
                if (regularDefList != null && !regularDefList.isEmpty()) {
                    for (DictScheduleRegularDef regularDef : regularDefList) {
                        cacheServiceImpl.clearRegularCache(regularDef.getRegularId());
                    }
                }
            }
            return JsonResultUtil.success("删除成功");
        }
        return JsonResultUtil.failure("删除失败");
    }

    @Override
    public JsonResult insertNewItemGroup(DictItemGroupDto dto) {
        String id = dictSerialService.getSerialId("GROUP_CODE");
        dto.setGroupCode(id);
        boolean insertResult = save(dto);
        if (insertResult) {
            String desc = "[项目分组] 名称:" + dto.getGroupName() + "分组类型" + ConstantsUtil.GroupType.getValue(dto.getGroupType()) + "检查类别" + dto.getExamClass();
            syslogService.saveLog(ConstantsUtil.ModuleName.ITEM_GROUP.name(), ConstantsUtil.OperateName.INSERT.getDesc(), desc);
            return JsonResultUtil.success("新增成功");
        }
        return JsonResultUtil.failure("新增失败");
    }
}
